package com.alks.function.service.impl.subcontractServiceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.alks.common.aop.AutoPageAop;
import com.alks.common.data.thread.UserIdThread;
import com.alks.common.utils.DateUtils;
import com.alks.common.utils.excelUtils.ExcelUtils;
import com.alks.common.utils.stringUtils.ZStringUtils;
import com.alks.entity.data.entity.sys.SysUser;
import com.alks.entity.data.entity.dispatch.OemLotHead;
import com.alks.entity.data.entity.dispatch.UserOemRelation;
import com.alks.entity.data.entity.dispatch.Vendor;
import com.alks.entity.data.entity.imes.Brand;
import com.alks.entity.data.entity.imes.BrandOemRelation;
import com.alks.entity.data.entity.imes.SysUserSub;
import com.alks.entity.data.response.ResponseInfo;
import com.alks.entity.exception.ServiceErrorException;
import com.alks.function.mapper.SdCompanyMapper;
import com.alks.function.mapper.SdUserMapper;
import com.alks.function.mapper.chengKong.PcLotHeadMapper;
import com.alks.function.mapper.subcontract.SubcontractMapper;
import com.alks.function.service.subcontract.SubcontractService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author:hxl
 * @create: 2024-07-25 10:05
 * @Description:
 */
@Service
public class SubcontractServiceImpl implements SubcontractService {
    @Autowired
    private SubcontractMapper subcontractMapper;

    @Autowired
    SdUserMapper sdUserMapper;

    @Override
    public ResponseInfo searchOemLotHead(OemLotHead oemLotHead) {
        Map<String, Object> map = new HashMap();
        Integer userId = sdUserMapper.getUserIdByLogin(UserIdThread.get().getLoginName());
        oemLotHead.setUserId(Long.valueOf(userId));
        oemLotHead.setCompanyId(UserIdThread.get().getCompanyId());
        PageHelper.startPage(oemLotHead.getPageNum(), oemLotHead.getPageSize());
        oemLotHead.setCompanyId(UserIdThread.get().getCompanyId());
        List<OemLotHead> list = subcontractMapper.searchOemLotHead(oemLotHead);
        Map<String, BigDecimal> summary = subcontractMapper.summary(oemLotHead);
        map.put("list", list);
        map.put("summary", summary);
        map.put("total", new PageInfo(list).getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo complete(OemLotHead oemLotHead) {
        oemLotHead = subcontractMapper.selectByUuid(oemLotHead);
        if (ZStringUtils.isNull(oemLotHead)) {
            throw new ServiceErrorException("无效的OEM指令记录");
        } else if (oemLotHead.isComplete()) {
            throw new ServiceErrorException("OEM指令已结案");
        } else {
            oemLotHead.setComplete(true);
            Integer i = subcontractMapper.complete(oemLotHead);
            if (i <= 0) return ResponseInfo.error("更新失败");
            else return ResponseInfo.ok("结案成功");
        }
    }

    @Override
    public ResponseInfo cancelComplete(OemLotHead oemLotHead) {
        oemLotHead = subcontractMapper.selectByUuid(oemLotHead);
        if (ZStringUtils.isNull(oemLotHead)) {
            throw new ServiceErrorException("无效的OEM指令记录");
        } else if (!oemLotHead.isComplete()) {
            throw new ServiceErrorException("OEM指令未结案");
        } else {
            oemLotHead.setComplete(false);
            Integer i = subcontractMapper.complete(oemLotHead);
            if (i <= 0) return ResponseInfo.error("更新失败");
            else return ResponseInfo.ok("取消结案成功");
        }
    }

    @Autowired
    PcLotHeadMapper pcLotHeadMapper;

    @Override
    @Transactional
    public ResponseInfo updatePrice(OemLotHead oemLotHead) {
        OemLotHead lotHead = pcLotHeadMapper.selectByFactoryLotNo(oemLotHead);
        if (lotHead == null)
            return ResponseInfo.error(ZStringUtils.format("工厂指令【{}】不存在，请核实！", new Object[]{oemLotHead.getFactoryLotNo()}));
        if (lotHead.isComplete())
            return ResponseInfo.error(ZStringUtils.format("工厂指令【{}】已结案，请核实！", new Object[]{oemLotHead.getFactoryLotNo()}));
        int payAmt = subcontractMapper.selectPayCfmCount(UserIdThread.get().getCompanyId(), oemLotHead.getFactoryLotNo());
        if (payAmt > 0)
            return ResponseInfo.error(ZStringUtils.format("工厂指令【{}】已对账检核无法修改,请核实", new Object[]{oemLotHead.getFactoryLotNo()}));
        subcontractMapper.insertOpLog(oemLotHead,UserIdThread.get());
        subcontractMapper.updatePrice(oemLotHead);
        return ResponseInfo.ok();
    }

    @Override
    @Transactional
    public ResponseInfo delete(OemLotHead oemLotHead) {
        oemLotHead = subcontractMapper.selectByUuid(oemLotHead);
        if (ZStringUtils.isNull(oemLotHead)) {
            throw new ServiceErrorException("无效的指令记录");
        } else if (oemLotHead.getCutQty() <= 0 && oemLotHead.getCraftQty() <= 0 && oemLotHead.getMatchQty() <= 0 && oemLotHead.getStitchQty() <= 0 && oemLotHead.getOutSoleQty() <= 0 && oemLotHead.getInsoleQty() <= 0 && oemLotHead.getFinishQty() <= 0) {
            subcontractMapper.deleteByLotUUID(oemLotHead);
            int outNum = subcontractMapper.selectByFactoryLotNo(oemLotHead);
            if (outNum > 0) {
                throw new ServiceErrorException("该指令已存在出库记录，无法删除");
            } else {
                subcontractMapper.deleteUuid(oemLotHead);
                return ResponseInfo.ok();
            }
        } else {
            throw new ServiceErrorException("该指令存在采集数据，无法删除");
        }
    }

    @Override
    public ResponseInfo oemCombo(String searchKey, List<String> vendorTypes) {
        List<Vendor> list = subcontractMapper.oemCombo(searchKey, vendorTypes, UserIdThread.get().getCompanyId());
        return ResponseInfo.ok(list);
    }

    @Override
    public void downloadOem(OemLotHead oemLotHead, HttpServletResponse response) throws IOException {
        Integer userId = sdUserMapper.getUserIdByLogin(UserIdThread.get().getLoginName());
        oemLotHead.setUserId(Long.valueOf(userId));
        oemLotHead.setCompanyId(UserIdThread.get().getCompanyId());
        List<OemLotHead> list = subcontractMapper.searchOemLotHead(oemLotHead);
        ArrayList<OemLotHead> heads = new ArrayList<>();
        for (OemLotHead head : list) {
            OemLotHead lotHead = new OemLotHead();
            BeanUtil.copyProperties(head, lotHead);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if (head.getCustomOrderDate() != null) lotHead.setCustomOrderTime(format.format(head.getCustomOrderDate()));
            if (head.getDeliveryDate() != null) lotHead.setDeliveryTime(format.format(head.getDeliveryDate()));
            if (head.getCreateDate() != null) lotHead.setCreateTime(format.format(head.getCreateDate()));
            heads.add(lotHead);
        }
        ExcelUtils.creatByTemplate(response, "OEM导出模板.xls", "OEM-LotHead-" + DateUtils.dateTimeNow(), heads);
    }

    @Override
    @AutoPageAop
    public ResponseInfo selectUserByRoleId(SysUserSub user) {
        user.setRoleId("52");
        Map<String, Object> map = new HashMap<>();
        List<SysUserSub> list = subcontractMapper.selectUserByRoleId(user);
        map.put("list", list);
        map.put("total", new PageInfo<SysUserSub>(list).getTotal());
        return ResponseInfo.ok(map);
    }

    @Override
    public ResponseInfo selectByUserId(Long userId) {
        List<UserOemRelation> list = subcontractMapper.selectByUserId(UserIdThread.get().getCompanyId(), userId);
        return ResponseInfo.ok(list);
    }

    @Autowired
    SdCompanyMapper sdCompanyMapper;

    @Override
    public ResponseInfo add(UserOemRelation userOemRelation) {
        userOemRelation.setCompanyId(UserIdThread.get().getCompanyId());
        int i = 0;
        SysUser user = sdUserMapper.selectUserWithRoleKey(userOemRelation.getUserId(), "subcontract_qc_role");
        if (user == null) {
            throw new ServiceErrorException("无效的QC人员信息");
        } else {
            Vendor vendor = sdCompanyMapper.selectOutVendorByName(userOemRelation.getCompanyId(), userOemRelation.getVendorAbbr(), "G17");
            if (vendor == null) {
                throw new ServiceErrorException("无效的OEM厂商");
            } else {
                userOemRelation.setVendorNo(vendor.getVendorNo());
                userOemRelation.setVendorAbbr(vendor.getVendorAbbr());
                UserOemRelation tempOemRelation = subcontractMapper.selectByUserVendor(userOemRelation);
                if (!Objects.isNull(tempOemRelation)) {
                    throw new ServiceErrorException("该OEM厂商已有，请勿重复添加！");
                } else {
                    userOemRelation.setCreateDate(new Date());
                    userOemRelation.setCreateUserId(UserIdThread.get().getUserId());
                    userOemRelation.setCreateUserName(UserIdThread.get().getUserName());
                    String string = UUID.randomUUID().toString().replaceAll("-", "");
                    userOemRelation.setUuid(string);
                    i = subcontractMapper.insert(userOemRelation);
                }
            }
        }
        if (i > 0) return ResponseInfo.ok("添加成功");
        return ResponseInfo.error("添加失败");
    }

    @Override
    public ResponseInfo deleteVendor(UserOemRelation userOemRelation) {
        int i = subcontractMapper.deleteVendor(userOemRelation);
        return ResponseInfo.ok(i);
    }

    @Override
    public ResponseInfo brandOemRelationslist(Long userId) {
        List<BrandOemRelation> list = subcontractMapper.brandOemRelationslist(UserIdThread.get().getCompanyId(), userId);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo addBrand(BrandOemRelation userOemRelation) {
        int i = 0 ;
        userOemRelation.setCompanyId(UserIdThread.get().getCompanyId());
        SysUser user =sdUserMapper.selectUserWithRoleKey(userOemRelation.getUserId(), "subcontract_qc_role");
        if (user == null) {
            throw new ServiceErrorException("无效的QC人员信息");
        }else {
            BrandOemRelation tempOemRelation = subcontractMapper.selectBrandByUserVendor(userOemRelation);
            if (!Objects.isNull(tempOemRelation)) {
                throw new ServiceErrorException("该品牌商已有，请勿重复添加！");
            } else {
                userOemRelation.setCreateDate(new Date());
                userOemRelation.setCreateUserId(UserIdThread.get().getUserId());
                userOemRelation.setCreateUserName(UserIdThread.get().getUserName());
                String string = UUID.randomUUID().toString().replaceAll("-", "");
                userOemRelation.setUuid(string);
                i =  subcontractMapper.insertBrand(userOemRelation);
            }
        }
        return ResponseInfo.ok(i);
    }

    @Override
    public ResponseInfo deleteBrand(BrandOemRelation userOemRelation) {
        int i = subcontractMapper.deleteBrand(userOemRelation);
        return ResponseInfo.ok(i);
    }

    @Override
    public ResponseInfo brandComboList() {
        List<Brand> list = subcontractMapper.brandComboList(UserIdThread.get().getCompanyId());
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo queryBrandList(Brand brand) {
        List<Brand> list = subcontractMapper.queryBrandList(brand);
        return ResponseInfo.ok(list);
    }

    @Override
    public ResponseInfo insertBrand(Brand brand) {
        brand.setCreateUser(UserIdThread.get().getLoginName());
        brand.setCreateTime(new Date());
        int seqNo = subcontractMapper.selectMaxSeqNo(brand)+1;
        brand.setSeqNo(seqNo);
        int num = subcontractMapper.repeatOrNotByName(brand);
        if (num > 0) {
            throw new ServiceErrorException("存在重复的编码或者名称,请确认!！");
        } else {
            int i =subcontractMapper.insertBrands(brand);
            return ResponseInfo.ok(i);
        }
    }

    @Override
    public ResponseInfo deleteBrands(Brand brand) {
        int usedCount = sdCompanyMapper.queryBrandUsedInSampleLotCount(brand.getBrandName());
        if (usedCount > 0) {
            throw new ServiceErrorException("该品牌已被使用,不能删除！");
        } else {
            return ResponseInfo.ok(sdCompanyMapper.deleteByRowId(brand));
        }
    }

    @Override
    public ResponseInfo deleteList(List<OemLotHead> list) {
        for (OemLotHead oemLotHead : list) {
            if (ZStringUtils.isNull(oemLotHead.getUuid())) return ResponseInfo.error("uuid不能为空");
            oemLotHead = subcontractMapper.selectByUuid(oemLotHead);
            if (ZStringUtils.isNull(oemLotHead)) {
                throw new ServiceErrorException("无效的指令记录");
            } else if (oemLotHead.getCutQty() <= 0 && oemLotHead.getCraftQty() <= 0 && oemLotHead.getMatchQty() <= 0 && oemLotHead.getStitchQty() <= 0 && oemLotHead.getOutSoleQty() <= 0 && oemLotHead.getInsoleQty() <= 0 && oemLotHead.getFinishQty() <= 0) {
                subcontractMapper.deleteByLotUUID(oemLotHead);
                int outNum = subcontractMapper.selectByFactoryLotNo(oemLotHead);
                if (outNum > 0) {
                    throw new ServiceErrorException("该指令已存在出库记录，无法删除");
                } else {
                    subcontractMapper.deleteUuid(oemLotHead);
                    return ResponseInfo.ok();
                }
            } else {
                throw new ServiceErrorException("该指令存在采集数据，无法删除");
            }
        }
        return null;
    }
}
